﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BaseCoder.Utility;
using System.IO;
using System.Text.RegularExpressions;
using BaseCoder.ManagePageCoder;
using System.Configuration;

namespace BaseCoder.ModelCoder
{
    public class ModelCreate
    {
        private ProjectConfig config = null;

        public ModelCreate(ProjectConfig config)
        {
            if (config == null) throw new Exception("没有给项目设定配置文件");
            this.config = config;
        }

        public void CreateModel()
        {
            Table[] tables = DBHelper.GetTables(config.ConectionString);
            if (tables.Length <= 0) return;
            for (int i = 0; i < tables.Length; i++)
            {
                CreateModelByTable(config.ConectionString, tables[i]);
                Console.WriteLine(tables[i].Name + " 实体类生成结束");
            }
        }
        public void CreateModelByTable(string connectionString, Table table)
        {
            if (config["ModelCover"] == "0" && File.Exists(config["ModelSavePath"] + table.Name + ".cs"))
            {
                Console.WriteLine(table.Name + " 已存在并且不可覆盖");
                return;
            }
            TableColumn[] columns = DBHelper.GetColumns(connectionString, table.Name);
            if (columns.Length <= 0) return;
            //ManageSettings.Create(table, columns);
            StringBuilder sb = new StringBuilder();
            sb.Append(GetDescription(table.Name, table.Description));
            sb.Append(GetNamespace());
            sb.Append("namespace " + config["ModelNamespace"] + "\n");
            sb.Append("{\n");
            if (!string.IsNullOrEmpty(table.Description))
            {
                sb.Append("     /// <summary>\n");
                sb.Append("     /// " + FormatDescrition(table.Description) + "\n");
                sb.Append("     /// </summary>\n");
            }
            sb.Append("     public class " + table.Name + "\n");
            sb.Append("     {\n");
            for (int i = 0; i < columns.Length; i++)
            {

                if (!string.IsNullOrEmpty(columns[i].Description))
                {
                    sb.Append("         /// <summary>\n");
                    sb.Append("         /// " + FormatDescrition(columns[i].Description) + "\n");
                    sb.Append("         /// </summary>\n");
                }
                sb.Append("         public " + DBHelper.GetCSharpDataType(columns[i].DbType) + " " + columns[i].ColName + " { get; set; }" + "\n\r");
            }
            sb.Append("     }\n");
            sb.Append("}\n");
            if (File.Exists(config["ModelSavePath"] + table.Name + ".cs")) File.Delete(config["ModelSavePath"] + table.Name + ".cs");
            FileStream fs = new FileStream(config["ModelSavePath"] + table.Name + ".cs", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.Flush();
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(sb.ToString());
            sw.Flush();
            sw.Close();

        }

        public string FormatDescrition(string desp)
        {
            Regex regex = new Regex("\r\n", RegexOptions.IgnoreCase);
            return regex.Replace(desp, "");
        }
        public string GetDescription(string tableName, string tableDescription)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("//----------------------------------------------------------------------------------------------------");
            sb.AppendLine("//Name:  " + tableName + "");
            sb.AppendLine("//Function:	" + FormatDescrition(tableDescription) + "" + " data model");
            sb.AppendLine("//Author:	BaseCoder");
            sb.AppendLine("//Date:    " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "");
            sb.AppendLine("//----------------------------------------------------------------------------------------------------");
            sb.AppendLine("//Change History:");
            sb.AppendLine(" // Date		Who		Changes Made");
            sb.AppendLine("//----------------------------------------------------------------------------------------------------");
            sb.AppendLine("//" + DateTime.Now.ToString("yyyy-MM-dd") + "	BaseCoder		create cs file");
            sb.AppendLine("//----------------------------------------------------------------------------------------------------\n");
            return sb.ToString();
        }
        public string GetNamespace()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("using System;\n");
            sb.Append("using System.Collections.Generic;\n");
            sb.Append("using System.Linq;\n");
            sb.Append("using System.Text;\n\n\r");
            return sb.ToString();
        }
    }
}
